#include "stdafx.h"
#include "BasicWindowLessObject.h"


#ifdef _DEBUG
#include "Windows.h"
#include <vector>
#include <assert.h>

namespace BASICWINDOWLESSEXUI
{
	using namespace std;

	class CBasicObjectDebugHelper{
	public:
		CBasicObjectDebugHelper(){
			InitializeCriticalSection(&m_cs);
		}
		~CBasicObjectDebugHelper(){

#ifdef _DEBUG
			if (m_vObject.size() != 0 )
			{
				OutputDebugString(L"\n\n*****************************  Warning:Object Free leave ******************\n\n");
			}
			else
			{
				OutputDebugString(L"\n\n******************************  Object Free Ok *****************************\n\n");
			}
#endif
			::DeleteCriticalSection(&m_cs);
		}
	public:
		void AddObject(CBasicWindowLessObject* pObj)
		{
			::EnterCriticalSection(&m_cs);
			m_vObject.push_back(pObj);
			::LeaveCriticalSection(&m_cs);
		}
		void RemoveObject(CBasicWindowLessObject* pObj)
		{
			::EnterCriticalSection(&m_cs);
			for(int i=0;i<(int)m_vObject.size();i++)
			{
				if (m_vObject[i] == pObj)
				{
					m_vObject.erase(m_vObject.begin()+i);
					break;
				}
			}
			::LeaveCriticalSection(&m_cs);
		}
	public:
		vector<CBasicWindowLessObject*>	m_vObject;
		CRITICAL_SECTION		m_cs;
	};

	CBasicObjectDebugHelper g_ObjectDebugHelper;

	volatile LONG gNewSkinObjectCount;
}
#endif

namespace BASICWINDOWLESSEXUI
{
	CBasicWindowLessObject::CBasicWindowLessObject()
		:m_nObjLockCount(1)
	{

#ifdef _DEBUG
		wchar_t buf[260];
		::InterlockedIncrement(&gNewSkinObjectCount);
		wsprintf(buf,L"New Object %d,count = %d\n",this,gNewSkinObjectCount);
		OutputDebugString(buf);
		g_ObjectDebugHelper.AddObject(this);
#endif
	}
	CBasicWindowLessObject::~CBasicWindowLessObject()
	{

#ifdef _DEBUG
		wchar_t buf[260];
		::InterlockedDecrement(&gNewSkinObjectCount);
		wsprintf(buf,L"Free Object %d,count = %d\n",this,gNewSkinObjectCount);
		OutputDebugString(buf);
		g_ObjectDebugHelper.RemoveObject(this);
#endif
	}

	int CBasicWindowLessObject::NsLockObject()
	{
		InterlockedIncrement(&m_nObjLockCount);
		return m_nObjLockCount;
	}

	bool CBasicWindowLessObject::NsUnlockObject()
	{
		if (InterlockedDecrement(&m_nObjLockCount)== 0)
		{
			delete this;
			return true;
		}
		return false;
	}
}

